<template>
    <view class="index-container">
        <Header pageTitle="首页" />

        <Weather :weatherInfo="weatherInfo" @temperature-change="handleTemperatureChange" />

        <view class="info-row">
            <view
                class="info-slider"
                @touchstart="touchStart"
                @touchmove="touchMove"
                @touchend="touchEnd">
                <view class="slider-inner" :style="{ transform: `translateX(${translateX}px)` }">
                    <view
                        class="notification-box"
                        @click="navigateTo('/pages/agriculture/agriculture')">
                        <view class="box-header">
                            <text class="header-title">消息提醒</text>
                            <image class="arrow-icon" src="/static/images/arrow-right.png"></image>
                        </view>
                        <view class="notification-list">
                            <view v-if="notifications.length === 0" class="empty-tip">
                                <text>暂无消息提醒</text>
                            </view>
                            <view
                                v-else
                                class="notification-item"
                                v-for="(item, index) in notifications"
                                :key="index">
                                <view
                                    class="notification-dot"
                                    :class="{
                                        'dot-warning': item.type === 'warning',
                                        'dot-danger': item.type === 'danger',
                                        'dot-success': item.type === 'success',
                                    }"></view>
                                <text class="notification-text">{{ item.content }}</text>
                                <text class="notification-time">{{ item.time }}</text>
                            </view>
                        </view>
                    </view>

                    <view
                        class="schedule-box"
                        @click="navigateTo('/pages/agriculture/agriculture')">
                        <view class="box-header">
                            <text class="header-title">今日安排</text>
                            <image class="arrow-icon" src="/static/images/arrow-right.png"></image>
                        </view>
                        <view class="schedule-list">
                            <view v-if="todaySchedule.length === 0" class="empty-tip">
                                <text>暂无今日安排</text>
                            </view>
                            <view
                                v-else
                                class="schedule-item"
                                v-for="(item, index) in todaySchedule"
                                :key="index">
                                <view class="schedule-dot green"></view>
                                <text class="schedule-text">{{ item.content }}</text>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <view class="management-box">
            <view class="section-title">农事管理</view>
            <view class="management-grid">
                <view
                    class="grid-item"
                    v-for="(item, index) in agricultureManagement"
                    :key="index"
                    @click="navigateTo(item.url)">
                    <view class="icon-box">
                        <image
                            class="icon-image"
                            :src="'/static/images/icons/' + item.icon + '.png'"></image>
                    </view>
                    <text class="item-text">{{ item.text }}</text>
                </view>
            </view>
        </view>

        <view class="management-box">
            <view class="section-title">仓库管理</view>
            <view class="management-grid">
                <view
                    class="grid-item"
                    v-for="(item, index) in warehouseManagement"
                    :key="index"
                    @click="navigateTo(item.url)">
                    <view class="icon-box">
                        <image
                            class="icon-image"
                            :src="'/static/images/icons/' + item.icon + '.png'"></image>
                    </view>
                    <text class="item-text">{{ item.text }}</text>
                </view>
            </view>
        </view> 

        <view class="management-box">
            <view class="section-title">智能管理</view>
            <view class="management-grid">
                <view
                    class="grid-item"
                    v-for="(item, index) in smartManagement"
                    :key="index"
                    @click="navigateTo(item.url)">
                    <view class="icon-box">
                        <image
                            class="icon-image"
                            :src="'/static/images/icons/' + item.icon + '.png'"></image>
                    </view>
                    <text class="item-text">{{ item.text }}</text>
                </view>
            </view>
        </view>

        <!-- AI聊天浮动按钮 -->
        <view class="ai-chat-float-btn" @click="navigateTo('/pages/smart/aiChat/aiChat')">
            <image class="ai-chat" src="/static/images/ai-chat.png"></image>
        </view>
    </view>
</template>

<script>
import { weatherInfo, notifications } from '@/utils/mockData.js'
import Header from '@/components/Header/index.vue'
import Weather from '@/components/Weather/index.vue'
import { getFarmingSchedulePage } from '@/utils/api/farmingSchedule.js'
import { farmingSchedule } from '@/utils/api/index.js'
import { AGRICULTURAL_WORK_TYPES, STATUS_DICT, getDictText } from '@/utils/dict.js'
export default {
    components: {
        Header,
        Weather,
    },
    data() {
        return {
            title: '首页',
            weatherInfo,
            notifications: [],
            todaySchedule: [],
            translateX: 0,
            startX: 0,
            isDragging: false,
            boxWidth: 0,
            maxTranslate: 0,
            currentTemperature: 0,
            agricultureManagement: [
                {
                    icon: 'data-statistics',
                    text: '数据统计',
                    url: '/pages/agriculture/statistics/statistics',
                },
                {
                    icon: 'calendar',
                    text: '农事计划',
                    url: '/pages/agriculture/agriculture',
                },
                {
                    icon: 'staff',
                    text: '用工管理',
                    url: '/pages/agriculture/staffManagement/staffManagement',
                },
                {
                    icon: 'seed',
                    text: '播种管理',
                    url: '/pages/agriculture/seedManagement/seedManagement',
                },
                {
                    icon: 'land',
                    text: '土地整备',
                    url: '/pages/agriculture/landPreparation/landPreparationList',
                },
                {
                    icon: 'irrigation',
                    text: '灌溉管理',
                    url: '/pages/agriculture/irrigationManagement/irrigationManagement',
                },
                {
                    icon: 'fertilizer',
                    text: '施肥管理',
                    url: '/pages/agriculture/fertilizerManagement/fertilizerManagement',
                },
                {
                    icon: 'protection',
                    text: '植保管理',
                    url: '/pages/agriculture/protectionManagement/protectionManagement',
                },
                {
                    icon: 'harvest',
                    text: '采收管理',
                    url: '/pages/agriculture/harvestManagement/harvestManagement',
                },
                {
                    icon: 'growth',
                    text: '作物生长',
                    url: '/pages/agriculture/growthManagement/growthManagement',
                },
                {
                    icon: 'disease',
                    text: '病虫草害',
                    url: '/pages/agriculture/diseaseManagement/diseaseManagement',
                },
                {
                    icon: 'weather',
                    text: '灾害天气',
                    url: '/pages/agriculture/weatherDisasterManagement/weatherDisasterManagement',
                },
            ],
            warehouseManagement: [
                {
                    icon: 'warehouse-in',
                    text: '农资入库',
                    url: '/pages/warehouse/warehouseIn/warehouseIn',
                },
                {
                    icon: 'warehouse-out',
                    text: '农资出库',
                    url: '/pages/warehouse/warehouseOut/warehouseOut',
                },
                {
                    icon: 'warehouse-statistics',
                    text: '库存统计',
                    url: '/pages/warehouse/statistics/statistics',
                },
            ],
            smartManagement: [
                {
                    icon: 'faucet',
                    text: '智能灌溉',
                    url: '/pages/smart/irrigation/irrigation',
                },
                {
                    icon: 'triangle-exclamation',
                    text: '土壤墒情',
                    url: '/pages/smart/soilMonitoring/soilMonitoring',
                },
                // {
                //     icon: 'task',
                //     text: 'AI聊天',
                //     url: '/pages/smart/aiChat/aiChat',
                // },
                {
                    icon: 'cloud-sun',
                    text: '环境气象',
                    url: '/pages/smart/weatherMonitoring/weatherMonitoring',
                },
                // {
                //     icon: 'temperature-high',
                //     text: '农情监测',
                //     url: '',
                // },
                {
                    icon: 'water',
                    text: '液位监测',
                    url: "/pages/smart/liquidLevel/liquidLevel",
                },
                // {
                //     icon: 'video',
                //     text: '安防监控',
                //     url: '',
                // },
            ],
        }
    },
    mounted() {
        // 获取设备宽度
        const info = uni.getSystemInfoSync()
        // 卡片宽度设为屏幕宽度的80%
        this.boxWidth = info.windowWidth * 0.8
        // 最大可以左移的距离
        this.maxTranslate = this.boxWidth * 0.8
        // 获取今日安排数据
        this.fetchTodaySchedule()
    },
    onLoad() {
        console.log('首页加载完成')
    },
    onShow() {
        this.initDictData()
    },
    onPullDownRefresh() {
        setTimeout(() => {
            uni.stopPullDownRefresh()
        }, 1000)
    },
    methods: {
        // 初始化加载字典数据
        async initDictData() {
            try {
                // 调用store中的action加载所有字典数据
                await this.$store.dispatch('getAllDictTypes')
                console.log('字典数据加载成功')
            } catch (error) {
                console.error('字典数据加载失败:', error)
            }
        },
        handleTemperatureChange(temperature) {
            this.currentTemperature = temperature
            if (temperature >= 36) {
                // 添加高温提醒到通知列表
                this.notifications.unshift({
                    type: 'warning',
                    content: `请注意明天气温${temperature}℃`,
                    time: new Date().toLocaleTimeString(),
                })
            }
        },
        getWorkTypeLabel(value) {
            if (!value) return '未命名任务'
            return getDictText(AGRICULTURAL_WORK_TYPES, value, value)
        },
        navigateTo(url) {
            if (url === '/pages/agriculture/agriculture') {
                uni.switchTab({
                    url,
                })
                return
            }
            uni.navigateTo({
                url: url,
            })
        },
        getIconBgColor(index) {
            const colors = [
                '#2196F3',
                '#4CAF50',
                '#FFC107',
                '#9C27B0',
                '#F44336',
                '#00BCD4',
                '#3F51B5',
                '#FF9800',
                '#8BC34A',
                '#795548',
                '#CDDC39',
                '#607D8B',
            ]
            return colors[index % colors.length]
        },
        touchStart(e) {
            this.startX = e.touches[0].clientX
            this.isDragging = true
        },
        touchMove(e) {
            if (!this.isDragging) return

            const currentX = e.touches[0].clientX
            const diff = currentX - this.startX

            // 计算新的位置
            let newTranslate = this.translateX + diff

            // 限制移动范围
            if (newTranslate > 0) {
                newTranslate = 0
            } else if (newTranslate < -this.maxTranslate) {
                newTranslate = -this.maxTranslate
            }

            this.translateX = newTranslate
            this.startX = currentX
        },
        touchEnd() {
            this.isDragging = false

            // 根据当前位置判断是回到起点还是移动到第二个卡片
            if (this.translateX < -this.maxTranslate / 2) {
                // 移动到第二个卡片
                this.translateX = -this.maxTranslate
            } else {
                // 回到起点
                this.translateX = 0
            }
        },

        async fetchTodaySchedule() {
            try {
                const today = new Date()
                const params = {
                    pageNum: 1,
                    pageSize: 2,
                    startDate: today.toISOString().split('T')[0],
                    endDate: today.toISOString().split('T')[0],
                }

                const res = await farmingSchedule.getFarmingSchedulePage(params)
                if (res.code === 0) {
                    console.log('任务列表：')
                    console.log(res.data.list)
                    this.todaySchedule = res.data.list.map((item) => ({
                        content: `${this.getWorkTypeLabel(item.workTask) || '未命名任务'} - ${
                            item.fieldName || ''
                        }`,
                    }))
                } else {
                    uni.showToast({ title: res.msg || '获取今日安排失败', icon: 'none' })
                }
            } catch (error) {
                console.error('获取今日安排失败:', error)
                uni.showToast({ title: '获取今日安排失败', icon: 'none' })
            }
        },
    },
}
</script>

<style scoped lang="scss">
.index-container {
    min-height: 100vh;
    padding: 0 0 150rpx 0;
    background-color: #f5f5f5;
    .top-bg {
        position: absolute;
        top: 0;
        left: 0;
        width: 750rpx;
    }
}

.header {
    display: flex;
    flex-direction: column;
    padding: 100rpx 32rpx 50rpx;

    .logo-title {
        position: relative;
        display: flex;
        align-items: flex-start;

        .logo {
            width: 72rpx;
            height: 72rpx;
            margin-right: 10rpx;
        }

        .title {
            font-family: OPPOSans, OPPOSans;
            font-weight: bold;
            font-size: 36rpx;
            color: #2d6040;
            line-height: 72rpx;
        }
    }

    .page-title {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 36rpx;
        color: #000000;
    }
}

.info-row {
    height: 340rpx;
    margin: 20rpx;

    .info-slider {
        width: 100%;
        height: 100%;
        overflow: hidden;
        position: relative;

        .slider-inner {
            display: flex;
            height: 100%;
            transition: transform 0.3s ease;
        }
    }

    .notification-box,
    .schedule-box {
        width: 80%;
        min-width: 80%;
        height: 100%;
        margin-right: 30rpx;
        border-radius: 12rpx;
        overflow: hidden;
        flex-shrink: 0;

        .box-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20rpx;

            .header-title {
                color: #fff;
                font-size: 28rpx;
                font-weight: 500;
            }

            .arrow-icon {
                width: 24rpx;
                height: 24rpx;
            }
        }

        .notification-list,
        .schedule-list {
            padding: 15rpx 20rpx;

            .empty-tip {
                display: flex;
                justify-content: center;
                align-items: center;
                margin-bottom: 24rpx;
                padding: 24rpx 24rpx;
                background: rgba(255, 255, 255, 0.09);
                border-bottom: 1px solid rgba(255, 255, 255, 0.1);
                text {
                    color: rgba(255, 255, 255, 0.8);
                    font-size: 26rpx;
                }
            }

            .notification-item,
            .schedule-item {
                margin-bottom: 24rpx;
                display: flex;
                align-items: center;
                padding: 24rpx 24rpx;
                background: rgba(255, 255, 255, 0.09);
            }

            .notification-text,
            .schedule-text {
                flex: 1;
                font-size: 26rpx;
            }

            .notification-time {
                font-size: 24rpx;
            }
        }
    }

    .notification-box {
        background-color: #175ecd;

        .box-header {
        }

        .notification-list {
            .notification-item {
                border-bottom: 1px solid rgba(255, 255, 255, 0.1);

                .notification-dot {
                    width: 15rpx;
                    height: 15rpx;
                    border-radius: 50%;
                    margin-right: 10rpx;
                    background-color: #fff;

                    &.dot-warning {
                        background-color: #ffd54f;
                    }

                    &.dot-danger {
                        background-color: #ff5252;
                    }

                    &.dot-success {
                        background-color: #81c784;
                    }
                }

                .notification-text {
                    color: #fff;
                }

                .notification-time {
                    color: rgba(255, 255, 255, 0.7);
                }
            }
        }
    }

    .schedule-box {
        background-color: #00b47e;

        .box-header {
        }

        .schedule-list {
            .schedule-item {
                border-bottom: 1px solid rgba(255, 255, 255, 0.1);
                background-color: rgba(255, 255, 255, 0.1);

                .schedule-dot {
                    width: 15rpx;
                    height: 15rpx;
                    border-radius: 50%;
                    margin-right: 10rpx;
                    background-color: #fff;
                }

                .schedule-text {
                    color: #fff;
                }
            }
        }
    }
}

.management-box {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .section-title {
        padding: 20rpx 30rpx;
        font-size: 30rpx;
        font-weight: 500;
        color: #333;
        border-bottom: 1px solid #f0f0f0;
    }

    .management-grid {
        display: flex;
        flex-wrap: wrap;
        padding: 20rpx 10rpx;

        .grid-item {
            width: 25%;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20rpx 0;

            .icon-box {
                width: 80rpx;
                height: 80rpx;
                border-radius: 10rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 12rpx;

                .icon-image {
                    width: 80rpx;
                    height: 80rpx;
                }
            }

            .item-text {
                font-family: OPPO Sans 4, OPPO Sans 40;
                font-weight: 400;
                font-size: 24rpx;
                color: rgba(0, 0, 0, 0.9);
            }
        }
    }
}

/* AI聊天浮动按钮 */
.ai-chat-float-btn {
    position: fixed;
    bottom: 120rpx;
    right: 40rpx;
    width: 150rpx;
    height: 150rpx;
    .ai-chat {
        width: 100%;
        height: 100%;
    }
}
</style>
